/*
 *   项目名称：train12306
 *   文件名称：com.xiaolon.train12306.common.util.JwtUtil
 *
 *   创建人：  ZHOU XIAO LONG
 *   创建日期：2024/12/24
 *
 */
package com.xiaolon.train12306.common.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.support.SimpleTriggerContext;

import java.util.HashMap;

/**
 * 类描述： JwtUtil
 * JWT工具类
 **/
public class JwtUtil {
    private static final Logger LOG = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 加盐，后期放配置文件
     */
    private static final String key = "xiaolon";

    /**
     * 根据用户登录信息，生成token
     * @param id
     * @param mobile
     * @return
     */
    public static String createToken(Long id, String mobile){
        DateTime now = DateTime.now();
        DateTime expTime = now.offsetNew(DateField.HOUR, 24);
        HashMap<String, Object> payload = new HashMap<>();
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间
        payload.put(JWTPayload.EXPIRES_AT, expTime);
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);

        // 内容
        payload.put("id", id);
        payload.put("mobile", mobile);
        String token = JWTUtil.createToken(payload, key.getBytes());
        LOG.info("生成JWT Token: {}", token);
        return token;
    }

    /**
     * 再次登录校验token
     * @param token
     * @return
     */
    public static boolean validate(String token){
        JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes());
        // validate包含了verify
        boolean validate = jwt.validate(0);
        LOG.info("JWT token校验结果: {}", validate);
        return validate;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static JSONObject getJSONObject(String token){
        JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes());
        JSONObject payloads = jwt.getPayloads();
        payloads.remove(JWTPayload.ISSUED_AT);
        payloads.remove(JWTPayload.EXPIRES_AT);
        payloads.remove(JWTPayload.NOT_BEFORE);
        LOG.info("根据token获取原始内容: {}", payloads);
        return payloads;
    }

    public static void main(String[] args) {

        createToken(1l, "123");
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE2NzY4OTk4MjcsIm1vYmlsZSI6IjEyMyIsImlkIjoxLCJleHAiOjE2NzY4OTk4MzcsImlhdCI6MTY3Njg5OTgyN30.JbFfdeNHhx";
        validate(token);

        getJSONObject(token);
    }

}